<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ page language="java" contentType="text/html;charset=utf-8"%>
<!doctype html>
<!--[if lt IE 7]><html lang="en-CA" class="no-js lt-ie9 lt-ie8 lt-ie7"><![endif]-->
<!--[if IE 7]><html lang="en-CA" class="no-js lt-ie9 lt-ie8"><![endif]-->
<!--[if IE 8]><html lang="en-CA" class="no-js lt-ie9"><![endif]-->
<!--[if gt IE 8]><!-->
<html lang="en-CA" class="no-js">
<!--<![endif]-->
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<title>Guhappy</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<%
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://"
				+ request.getServerName() + ":" + request.getServerPort()
				+ path + "/";
	%>
	<base href="<%=basePath%>">
	<link href="css/bootstrap.min.css" rel="stylesheet">
	<link href="css/header.css" rel="stylesheet">
	<link href="css/common.css" rel="stylesheet">
	
		<!--Load the AJAX API-->
	<script type="text/javascript" src="https://www.google.com/jsapi"></script>
	<script type="text/javascript">
		// Callback that creates and populates a data table,
		// instantiates the pie chart, passes in the data and
		// draws it.
	
		function drawStatesMap() {
			$.ajax({
				url : "jsoncharts.action",
				data: {'area':'<s:property value="%{area}" />', 'stockID':'<s:property value="%{stockbean.id}" />'},
				dataType : "JSON"
			}).done(
					function(data) {
						var array1 = [ [ "Date", "price" ] ];
						var array2 = [ [ "Date", "vol(M)" ] ];
						$.each(data.priceList, function() {
							var item1 = [ this.stock_date, this.price ];
							var item2 = [ this.stock_date, this.vol ];
							array1.push(item1);
							array2.push(item2);
						});
						var options1 = {
						          title: '1-Year Price',
						          hAxis: { format:'M/d/yy',  gridlines: {count: 12}},
						          vAxis: {minValue: data.min, maxValue: data.max}
						        };

						var data1 = google.visualization
								.arrayToDataTable(array1);
						var chart = new google.visualization.AreaChart(document
								.getElementById('chart_div'));
						chart.draw(data1, options1);
						
						var options2 = {
								  chartArea:{top:5},
						          title: 'Volume',
						          hAxis: { textPosition: 'none',  format:'M/d/yy',  gridlines: {count: 6} },
						          vAxis: {},
						          interpolateNulls: true
						        };
						var data2 = google.visualization.arrayToDataTable(array2);
						var chart2 = new google.visualization.ColumnChart(document.getElementById('chart_div2'));
				        chart2.draw(data2, options2);
				        var data3 = google.visualization.arrayToDataTable([
				                                                          ['Which', 'win'],
				                                                          ['BeatIndex',     data.bBean.beatIndexWeekly],
				                                                          ['IndexWin',      data.bBean.lostIndexWeekly]
				                                                        ]);
						var options3 = {
							title : 'Weekly'
						};

						var chart3 = new google.visualization.PieChart(document
								.getElementById('chart_div3'));

						chart3.draw(data3, options3);

					    var data4 = google.visualization.arrayToDataTable([
					                                                          ['Which', 'win'],
					                                                          ['BeatIndex',     data.bBean.beatIndexMonthly],
					                                                          ['IndexWin',      data.bBean.lostIndexMonthly]
					                                                        ]);
						var options4 = {
							title : 'Monthly'
						};

						var chart4 = new google.visualization.PieChart(document
								.getElementById('chart_div4'));

						chart4.draw(data4, options4);


					    var data5 = google.visualization.arrayToDataTable([
					                                                          ['Which', 'win'],
					                                                          ['BeatIndex',     data.bBean.beatIndexQuaterly],
					                                                          ['IndexWin',      data.bBean.lostIndexQuaterly]
					                                                        ]);
						var options5 = {
							title : 'Quarterly'
						};

						var chart5 = new google.visualization.PieChart(document
								.getElementById('chart_div5'));

						chart5.draw(data5, options5);


					    var data6 = google.visualization.arrayToDataTable([
					                                                          ['Which', 'win'],
					                                                          ['BeatIndex',     data.bBean.beatIndexYearly],
					                                                          ['IndexWin',      data.bBean.lostIndexYearly]
					                                                        ]);
						var options6 = {
							title : 'Annualy'
						};

						var chart6 = new google.visualization.PieChart(document
								.getElementById('chart_div6'));

						chart6.draw(data6, options6);

					});
		}
		google.load('visualization', '1', {
			'packages' : [ 'corechart' ]
		});
		google.setOnLoadCallback(drawStatesMap);
	</script>
	
</head>
<body>
	<jsp:include page="header.jsp" />
	<div class="container" style="margin-top:60px">
		<div class="row">
			<div class="col-md-7 col-md-offset-2">
				<div id='popularStocks' class='marquee-with-options'></div>
			</div>
		</div>
		<table class="col-md-12">
			<tbody>
				<tr>
					<td class="col-md-6"  valign="top">
						<h4>
							<b id='company-title'>a</b>
						</h4> 
						<span style='color: #228822'>Discription:</span>
						<div class="accordion" id="accordion_desc">
                              <div class="accordion-group">
                                    <div class="accordion-heading">
                                          <span id='company-desc'></span>
                                          <a id="desc-more" data-toggle="collapse" data-target="#collapseDesc">Read More...</a>
                                    </div>
                                    <div id="collapseDesc" class="collapse">
                                          <div id="company-decs-more"></div>
                                          <a data-toggle="collapse" href="#collapseDesc">Read Less</a>
                                    </div>
                              </div>
                        </div>
						<span style='color: #228822'>Company News:</span>
						<div class="accordion" id="accordion_news">
							<div class="accordion-group">
								<div class="accordion-heading">
									<span id='company-news'>News:</span> 
									<a id="news-more" data-toggle="collapse" 
										href="#collapseNews"> Read More... </a>
								</div>
								<div id="collapseNews" class="collapse">
									<div id="company-news-more">News:</div>
									<a data-toggle="collapse" href="#collapseNews">Read
										Less</a>
								</div>
							</div>
						</div>
						<span style='color: #228822'>Market:</span>
						<div class="row-fluid">
							<div class="col-md-6">
								Previous Close:<span id="company-previous"></span>
							</div>
							<div class="col-md-6">
								Volume:<span id="company-volume"></span>
							</div>
						</div>
						<div class="row-fluid">
							<div class="col-md-6">
								Today Open:<span id="company-open"></span>
							</div>
							<div class="col-md-6">
								Average Volume:<span id="company-avg"></span>
							</div>
						</div>
						<div class="row-fluid">
							<div class="col-md-6">
								Daily Low:<span id="company-low"></span>
							</div>
							<div class="col-md-6">
								Daily High:<span id="company-high"></span>
							</div>
						</div>
						<div class="row-fluid">
							<div class="col-md-6">
								1 year Low:<span id="company-hislow"></span>
							</div>
							<div class="col-md-6">
								1 year High:<span id="company-hishigh"></span>
							</div>
						</div>
						<div class="row-fluid">
							<div class="col-md-6">
								P/E(TTM):<span id="company-pe"></span>
							</div>
							<div class="col-md-6">
								Div./Yield:<span id="company-div"></span>
							</div>
						</div> <span style='color: #228822'>Stock Compares:</span>
						<div class="row-fluid">
							<div class="col-md-4">
								vs index:<span id="compare-index"></span>
							</div>
							<div class="col-md-4">
								vs sector:<span id="company-div"></span>
							</div>
							<div class="col-md-4">
								vs stock:<span id="company-div"></span>
							</div>
						</div>
						<div class="row">
							<div class="col-md-4"></div>
							<div class="col-md-4"></div>
							<div class="col-md-4"></div>
						</div> <span style='color: #228822'>Game records:</span><br>
						Games:<span id="game-count">12</span>&nbsp;Won:<span
						id="game-won">3</span>&nbsp;Selected:<span id="game-selected">60</span>
					</td>
					<td valign="top">
							<div id="chart_div" style="width: 686px; height: 201px;"></div>
					        <div id="chart_div2" style="width: 686px; height: 201px;"></div>
					        <div class="row">
							  <div class="col-xs-6" id="chart_div3" style="display: inline-block; height: 101px; position: relative;"></div>
							  <div class="col-xs-6" id="chart_div4" style="display: inline-block; height: 101px; position: relative;"></div>
							</div>
							<div class="row">
							  <div class="col-xs-6" id="chart_div5" style="display: inline-block; height: 101px; position: relative;"></div>
							  <div class="col-xs-6" id="chart_div6" style="display: inline-block; height: 101px; position: relative;"></div>
							</div>
					</td>
				</tr>
				<tr>
					<th colspan="2">
						<div id="holder" class="container" >
							<div id="template">
								<div class="row" id="bull" style="margin-top:20px">
									<div style="text-align:center" class="col-md-1">
										<img src="./images/bull.PNG" />
										<div class="col-xs-0" style="margin-top:20px">
											Votes:
										</div>
									</div>
									<div style="text-align:center" class="col-md-2">
										<div class="contest_type bull">
											<div>3-DAYS</div>
											<div id="days_end">ends at: end_date</div>
										</div><br>
										<div id="days_votes" style="margin-top:12px;margin-bottom:12px">
											days_votes
										</div>
										<div style="margin-top:5px">
											<button class="btn btn-green" type="submit" >Vote</button>
										</div>
									</div>
									<div style="text-align:center" class="col-md-2">
										<div class="contest_type bull">
											<div>WEEK</div>
											<div id="week_end">ends at: end_date</div>
										</div><br>
										<div id="week_votes" style="margin-top:12px;margin-bottom:12px">
											week_votes
										</div>
										<div style="margin-top:5px">
											<button class="btn btn-green" type="submit" >Vote</button>
										</div>
									</div>
									<div style="text-align:center" class="col-md-2">
										<div class="contest_type bull">
											<div>MONTH</div>
											<div id="month_end">ends at: end_date</div>
										</div><br>
										<div id="month_votes" style="margin-top:12px;margin-bottom:12px">
											month_votes
										</div>
										<div style="margin-top:5px">
											<button class="btn btn-green" type="submit" >Vote</button>
										</div>
									</div>
									<div style="text-align:center" class="col-md-2">
										<div class="contest_type bull">
											<div>QUARTER</div>
											<div id="quarter_end">ends at: end_date</div>
										</div><br>
										<div id="quarter_votes" style="margin-top:12px;margin-bottom:12px">
											quarter_votes
										</div>
										<div style="margin-top:5px">
											<button class="btn btn-green" type="submit" >Vote</button>
										</div>
									</div>
									<div style="text-align:center" class="col-md-2">
										<div class="contest_type bull">
											<div>YEAR</div>
											<div id="year_end">ends at: end_date</div>
										</div><br>
										<div id="year_votes" style="margin-top:12px;margin-bottom:12px">
											year_votes
										</div>
										<div style="margin-top:5px">
											<button class="btn btn-green" type="submit" >Vote</button>
										</div>
									</div>
								</div>
								<div class="row" id="bear" style="margin-top:20px">
									<div style="text-align:center" class="col-md-1">
										<img src="images/bear.PNG" />
										<div style="margin-top:20px">
											Votes:
										</div>
									</div>
									<div style="text-align:center" class="col-md-2">
										<div class="contest_type bear">
											<div>3-DAYS</div>
											<div id="days_end">ends at: end_date</div>
										</div><br>
										<div id="days_votes" style="margin-top:12px;margin-bottom:12px">
											days_votes
										</div>
										<div style="margin-top:5px">
											<button class="btn btn-red" type="submit" >Vote</button>
										</div>
									</div>
									<div style="text-align:center" class="col-md-2">
										<div class="contest_type bear">
											<div>WEEK</div>
											<div id="week_end">ends at: end_date</div>
										</div><br>
										<div id="week_votes" style="margin-top:12px;margin-bottom:12px">
											week_votes
										</div>
										<div style="margin-top:5px">
											<button class="btn btn-red" type="submit" >Vote</button>
										</div>
									</div>
									<div style="text-align:center" class="col-md-2">
										<div class="contest_type bear">
											<div>MONTH</div>
											<div id="month_end">ends at: end_date</div>
										</div><br>
										<div id="month_votes" style="margin-top:12px;margin-bottom:12px">
											month_votes
										</div>
										<div style="margin-top:5px">
											<button class="btn btn-red" type="submit" >Vote</button>
										</div>
									</div>
									<div style="text-align:center" class="col-md-2">
										<div class="contest_type bear">
											<div>QUARTER</div>
											<div id="quarter_end">ends at: end_date</div>
										</div><br>
										<div id="quarter_votes" style="margin-top:12px;margin-bottom:12px">
											quarter_votes
										</div>
										<div style="margin-top:5px">
											<button class="btn btn-red" type="submit" >Vote</button>
										</div>
									</div>
									<div style="text-align:center" class="col-md-2">
										<div class="contest_type bear">
											<div>YEAR</div>
											<div id="year_end">ends at: end_date</div>
										</div><br>
										<div id="year_votes" style="margin-top:12px;margin-bottom:12px">
											year_votes
										</div>
										<div style="margin-top:5px">
											<button class="btn btn-red" type="submit" >Vote</button>
										</div>
									</div>
								</div>
							</div>
						</div>
					</th>
				</tr>
			</tbody>
		</table>
	</div>
	<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
	<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
	<script type="text/javascript" src="js/bar.js"></script>
	<script type="text/javascript" src="js/header.js"></script>
	<script src="js/typeahead_bundle.js"></script>
	<script type="text/javascript" src="js/guhappy.js"></script>
	<script>
	(function($) {
	    function getStock(opts, type, complete) {
	        var defs = {
	            desc: false,
	            baseURL: 'http://query.yahooapis.com/v1/public/yql?q=',
	            query: {
	                quotes: 'select * from yahoo.finance.quotes where symbol = "{stock}" | sort(field="{sortBy}", descending="{desc}")',
	                historicaldata: 'select * from yahoo.finance.historicaldata where symbol = "{stock}" and startDate = "{startDate}" and endDate = "{endDate}"'
	            },
	            suffixURL: {
	                quotes: '&env=store://datatables.org/alltableswithkeys&format=json&callback=?',
	                historicaldata: '&env=store://datatables.org/alltableswithkeys&format=json&callback=?'
	            }
	        };
	        opts = opts || {};
	        if (!opts.stock) {
	            complete('No stock defined');
	            return;
	        }
	        var query = defs.query[type]
	        .replace('{stock}', opts.stock)
	        .replace('{sortBy}', defs.sortBy)
	        .replace('{desc}', defs.desc)
	        .replace('{startDate}', opts.startDate)
	        .replace('{endDate}', opts.endDate)
	       var url = defs.baseURL + query + (defs.suffixURL[type] || '');
	        $.getJSON(url, function(data) {
	            var err = null;
	            if (!data || !data.query) {
	                err = true;
	            }
	            complete(err, !err && data.query.results);    });
	    }
	    window.getStock = getStock;
	})(jQuery);
	
	var maxNews = 2;
	var maxDesc = 160;
	var descStop = 0;
	$.ajax(
			   {
			      type:'GET',
			      url:'/createUser',
			      data:"userId=12345&userName=test",
			      success: function(data){
			        alert('successful');
			      }
			   }
			);
	$(function() {
		$('.accordion').each( function(index) {
		    $(this).on('show.bs.collapse', function(e) {
		    	var $tt=$(e.target);
		    	$(e.target).prev('.accordion-heading').find('> a').text(function(i,origText){ 
					return "";
		    	 });
		    });
		    $(this).on('hidden.bs.collapse', function (e) {
				$(e.target).prev('.accordion-heading').find('> a').text(function(i,origText){
					return "Read More..."; 
				});
		    });
		});
		
		$("#company-title").text(function(i,origText){
			return '<s:property value="%{stockbean.company.name}" />' + ' (' + '<s:property value="%{stockbean.sticker}" />'+')'; 
		});
		
		getStock({ stock: '<s:property value="%{stockbean.sticker}" />' }, 'quotes', function(err, data) {
			$("#company-previous").text(function(i,origText){
				return data.quote.PreviousClose;
			});
			$("#company-volume").text(function(i,origText){
				return data.quote.Volume; 
			});
			$("#company-open").text(function(i,origText){
				return data.quote.Open; 
			});
			$("#company-avg").text(function(i,origText){
				return data.quote.AverageDailyVolume; 
			});
			$("#company-low").text(function(i,origText){
				return data.quote.DaysLow; 
			});
			$("#company-high").text(function(i,origText){
				return data.quote.DaysHigh; 
			});
			$("#company-hislow").text(function(i,origText){
				return data.quote.YearLow; 
			});
			$("#company-hishigh").text(function(i,origText){
				return data.quote.YearHigh; 
			});
			$("#company-pe").text(function(i,origText){
				return data.quote.PEGRatio; 
			});
			$("#company-div").text(function(i,origText){
				return data.quote.DividendShare; 
			});
		});
	
		$.jGFeed('http://finance.yahoo.com/rss/headline?s=' + '<s:property value="%{stockbean.sticker}" />',
				  function(feeds){
				    // Check for errors
				    if(!feeds){
				      // there was an error
				      return false;
				    }

				    $("#company-news").html(function(i,origHtml){
						var html = "";
						for(var i in feeds.entries) {
							if( i < maxNews ) {
								if (feeds.entries[i].title = "Yahoo! Finance: RSS feed not found") return false;
								if(html.length > 0) html += "<br>";
								html += "<a target='_blank' href='";
								html += feeds.entries[i].link;
								html += "'>";
								html += feeds.entries[i].title;
								html += " (";
								html += feeds.entries[i].publishedDate;
								html += ") </a>";
							}
							else break;
						}
						return html; 
					});
				    $("#news-more").text(function(i,origText){
						if(feeds.entries.length > maxNews) {
							return origText;
						}
						return ""; 
					});
					$("#company-news-more").html(function(i,origHtml){
						var html = "";
						var i = maxNews;
						for(i; i < feeds.entries.length; ++i) {
							if(html.length > 0) html += "<br>";
							html += "<a target='_blank'  href='";
							html += feeds.entries[i].link;
							html += "'>";
							html += feeds.entries[i].title;
							html += " (";
							html += feeds.entries[i].publishedDate;
							html += ") </a>";
						}
						$('.accordion-body').collapse('hide');
						return html; 
					});
				  }, 3);
		var areaCode = '<s:property value="%{area}" />';
		var query1 = "select * from html where url='http://finance.yahoo.com/q/pr?s=" + '<s:property value="%{stockbean.sticker}" />'+"' and xpath='";
		var query2 = '//p[2][preceding::table[1][contains(@class,"yfnc_modtitle1")]//span [.="Business Summary"]]'+"'";
		var stockName = '<s:property value="%{stockbean.sticker}" />';
		if (areaCode == 'China'){
			if (stockName.indexOf(".S") > -1)
				{
				stockName ='s'+stockName.substring(0, 6);
				}
		}
		var query3 = "select * from html where url='http://stockdata.stock.hexun.com/gszl/" + stockName +".shtml' and xpath='";
		var query4 = '//div[contains(@class,"xinx_l")]/p'+"'";
		$.ajax(
				   {
				      type:'GET',
				      url: (areaCode == 'China')?'https://query.yahooapis.com/v1/public/yql?q='+query3+query4:'https://query.yahooapis.com/v1/public/yql?q='+query1+query2,
				      dataType: 'xml',
				      success: function(data){
				    	  if (data) {
				    		  var strDesc =  $(data).find('results').find('p:nth-child(2)').text()+'\n'+ $(data).find('results').find('p:first').text();
                              if(strDesc.length > maxDesc) {
                       	  		descStop = (areaCode == 'China')?strDesc.indexOf('。', maxDesc) + 1:strDesc.indexOf('.', maxDesc) + 1;
                                $("#company-desc").html(strDesc.substring(0, descStop).replace(/\n/g, '<br />'));
                                $("#desc-more").show();
                                $("#company-decs-more").html(strDesc.substring(descStop).replace(/\n/g, '<br />'));
                               } else {
                                 $("#company-desc").html(strDesc.replace(/\n/g, '<br />'));
                                 $("#desc-more").hide();
                               }
				          }
				      }
				  });
		$.ajax({
	        type: "POST",
	        dataType: 'json',
	        url: 'jsonrollingstocks.action',
	        data: {'area':'<s:property value="%{area}" />'},
	        success:function(data){
				var html = '';
				for(var i in data.stock) {
					var inner = '<span class="popularStock" style="color:';
					var stock = data.stock[i];
					if(stock.change.indexOf('-') > -1) {
						inner += '#AA1111;">';
					}
					else {
						inner += '#228822;">';
					}
					inner += stock.symbol + ' ' + stock.change + '</span>&nbsp;&nbsp;&nbsp;&nbsp;';
					html += inner;
				}
				
				$("#popularStocks").html(function(i,origHtml){
					return html; 
				});
				
				$("#popularStocks").marquee();
			}, 
	        error: function (request, status, error) {
	        }

	    });
		
		var $clone = $('#template').clone();
		var $template;
		$.get("data/stockView.json",function(data,status){
			if(status=="success") {
				var data = JSON && JSON.parse(JSON.stringify(data)) || $.parseJSON(data);
				for(var i in data.stocks) {
					var stock = data.stocks[i];
					if(i > 0) {
						$template = $clone.clone();
						$('#holder').append($template);
					}
					else {
						$template = $('#template');
					}
					
					var $bull = $template.find("#bull");
					$bull.find("#days_end").text(function(i,origText){
						var text = origText.replace("end_date", stock.bull.days_end);
						return text; 
					});
					$bull.find("#days_votes").text(function(i,origText){
						var text = stock.bull.days_votes;
						return text; 
					});
					$bull.find("#week_end").text(function(i,origText){
						var text = origText.replace("end_date", stock.bull.week_end);
						return text; 
					});
					$bull.find("#week_votes").text(function(i,origText){
						var text = stock.bull.week_votes;
						return text; 
					});
					$bull.find("#month_end").text(function(i,origText){
						var text = origText.replace("end_date", stock.bull.month_end);
						return text; 
					});
					$bull.find("#month_votes").text(function(i,origText){
						var text = stock.bull.month_votes;
						return text; 
					});
					$bull.find("#quarter_end").text(function(i,origText){
						var text = origText.replace("end_date", stock.bull.quarter_end);
						return text; 
					});
					$bull.find("#quarter_votes").text(function(i,origText){
						var text = stock.bull.quarter_votes;
						return text; 
					});
					$bull.find("#year_end").text(function(i,origText){
						var text = origText.replace("end_date", stock.bull.year_end);
						return text; 
					});
					$bull.find("#year_votes").text(function(i,origText){
						var text = stock.bull.year_votes;
						return text; 
					});
					
					var $bear = $template.find("#bear");
					$bear.find("#days_end").text(function(i,origText){
						var text = origText.replace("end_date", stock.bull.days_end);
						return text; 
					});
					$bear.find("#days_votes").text(function(i,origText){
						var text = stock.bear.days_votes;
						return text; 
					});
					$bear.find("#week_end").text(function(i,origText){
						var text = origText.replace("end_date", stock.bull.week_end);
						return text; 
					});
					$bear.find("#week_votes").text(function(i,origText){
						var text = stock.bear.week_votes;
						return text; 
					});
					$bear.find("#month_end").text(function(i,origText){
						var text = origText.replace("end_date", stock.bull.month_end);
						return text; 
					});
					$bear.find("#month_votes").text(function(i,origText){
						var text = stock.bear.month_votes;
						return text; 
					});
					$bear.find("#quarter_end").text(function(i,origText){
						var text = origText.replace("end_date", stock.bull.quarter_end);
						return text; 
					});
					$bear.find("#quarter_votes").text(function(i,origText){
						var text = stock.bear.quarter_votes;
						return text; 
					});
					$bear.find("#year_end").text(function(i,origText){
						var text = origText.replace("end_date", stock.bull.year_end);
						return text; 
					});
					$bear.find("#year_votes").text(function(i,origText){
						var text = stock.bear.year_votes;
						return text; 
					});
				}
			}
		});
	})
	</script>
</body>
</html>